<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico">
  <link rel="mask-icon" href="/images/favicon.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css" integrity="sha256-mUZM63G8m73Mcidfrv5E+Y61y7a12O5mW4ezU3bxqW4=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.8.0","exturl":false,"sidebar":{"position":"left","display":"remove","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":"false;","trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>
<meta name="description" content="1.Mybatis简介1.1原始jdbc操作（查询数据） 1.2原始jdbc操作（插入数据）">
<meta property="og:type" content="article">
<meta property="og:title" content="Mybatis 学习（一）">
<meta property="og:url" content="http://example.com/2021/09/04/mybatis%E7%AC%94%E8%AE%B0(%E4%B8%80)/index.html">
<meta property="og:site_name" content="ADGai&#39;s Blog">
<meta property="og:description" content="1.Mybatis简介1.1原始jdbc操作（查询数据） 1.2原始jdbc操作（插入数据）">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%871.png">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%872.png">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%873.png">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%875.png">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%876.png">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%877.png">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%878.png">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%879.png">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%8710.png">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%8711.png">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%8712.png">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%8713.png">
<meta property="og:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%8714.png">
<meta property="article:published_time" content="2021-09-04T14:32:51.514Z">
<meta property="article:modified_time" content="2021-10-26T09:20:01.198Z">
<meta property="article:author" content="AiLaodu">
<meta property="article:tag" content="Mybatis">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%871.png">


<link rel="canonical" href="http://example.com/2021/09/04/mybatis%E7%AC%94%E8%AE%B0(%E4%B8%80)/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://example.com/2021/09/04/mybatis%E7%AC%94%E8%AE%B0(%E4%B8%80)/","path":"2021/09/04/mybatis笔记(一)/","title":"Mybatis 学习（一）"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Mybatis 学习（一） | ADGai's Blog</title>
  




  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">ADGai's Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container"></div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container">
  <div class="algolia-stats"><hr></div>
  <div class="algolia-hits"></div>
  <div class="algolia-pagination"></div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/04/mybatis%E7%AC%94%E8%AE%B0(%E4%B8%80)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="AiLaodu">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="ADGai's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Mybatis 学习（一）
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-09-04 22:32:51" itemprop="dateCreated datePublished" datetime="2021-09-04T22:32:51+08:00">2021-09-04</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-10-26 17:20:01" itemprop="dateModified" datetime="2021-10-26T17:20:01+08:00">2021-10-26</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Mybatis/" itemprop="url" rel="index"><span itemprop="name">Mybatis</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h3 id="1-Mybatis简介"><a href="#1-Mybatis简介" class="headerlink" title="1.Mybatis简介"></a>1.Mybatis简介</h3><h4 id="1-1原始jdbc操作（查询数据）"><a href="#1-1原始jdbc操作（查询数据）" class="headerlink" title="1.1原始jdbc操作（查询数据）"></a>1.1原始jdbc操作（查询数据）</h4><p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%871.png"></p>
<h4 id="1-2原始jdbc操作（插入数据）"><a href="#1-2原始jdbc操作（插入数据）" class="headerlink" title="1.2原始jdbc操作（插入数据）"></a>1.2原始jdbc操作（插入数据）</h4><span id="more"></span>

<p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%872.png"></p>
<h4 id="1-3-原始jdbc操作的分析"><a href="#1-3-原始jdbc操作的分析" class="headerlink" title="1.3 原始jdbc操作的分析"></a>1.3 原始jdbc操作的分析</h4><p>原始jdbc开发存在的问题如下：</p>
<p>①数据库连接创建、释放频繁造成系统资源浪费从而影响系统性能</p>
<p>②sql 语句在代码中硬编码，造成代码不易维护，实际应用 sql 变化的可能较大，sql 变动需要改变java代码。</p>
<p>③查询操作时，需要手动将结果集中的数据手动封装到实体中。插入操作时，需要手动将实体的数据设置到sql语句的占位符位置</p>
<p>应对上述问题给出的解决方案：</p>
<p>①使用数据库连接池初始化连接资源</p>
<p>②将sql语句抽取到xml配置文件中</p>
<p>③使用反射、内省等底层技术，自动将实体与表进行属性与字段的自动映射</p>
<h4 id="1-4-什么是Mybatis"><a href="#1-4-什么是Mybatis" class="headerlink" title="1.4 什么是Mybatis"></a>1.4 什么是Mybatis</h4><p>mybatis 是一个优秀的基于java的持久层框架，它内部封装了jdbc，使开发者只需要关注sql语句本身，而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。</p>
<p>mybatis通过xml或注解的方式将要执行的各种 statement配置起来，并通过java对象和statement中sql的动态参数进行映射生成最终执行的sql语句。</p>
<p>最后mybatis框架执行sql并将结果映射为java对象并返回。采用<strong>ORM思想</strong>(对象关系映射（Object Relational Mapping))解决了实体和数据库映射的问题，对jdbc 进行了封装，屏蔽了jdbc API 底层访问细节，使我们不用与jdbc API 打交道，就可以完成对数据库的持久化操作。</p>
<h5 id="ORM思想"><a href="#ORM思想" class="headerlink" title="ORM思想"></a>ORM思想</h5><p>**O(对象模型)**：实体对象，即我们在程序中根据数据库表结构建立的一个个实体Entity。</p>
<p>**R(关系型数据库的数据结构)**：即我们建立的数据库表。</p>
<p>**M(映射)**：从 R(数据库) 到 O(对象模型) 的映射，可通过XML文件映射。</p>
<p><strong>为什么使用ORM？</strong>提高开发效率：ORM框架自动实现Entity实体的属性与关系型数据库字段的映射。CRUD的工作则可以交给ORM来自动生成代码方式实现。隐藏了数据访问细节，“封闭”的通用数据库交互，他使得我们的通用数据库交互变得简单易行，并且完全不用考虑SQL语句。大大提高我们开发效率， 这样一来也减少我们维护一个复杂 缺乏灵活性数据访问层的成本。</p>
<p>ORM作为是一种思想，帮助我们开发人员跟踪实体的变化,并将实体的变化翻译成sql脚本,执行到数据库中去,也就是将实体的变化映射到了表的变化。这样会给我们带来非常大的便利。但有得必有失，便利的同时也无可避免的带来了一些其他的问题：比如性能降低，复杂的查询ORM仍然力不从心等。</p>
<h3 id="2-Mybatis的快速入门"><a href="#2-Mybatis的快速入门" class="headerlink" title="2.Mybatis的快速入门"></a>2.Mybatis的快速入门</h3><h4 id="2-1-MyBatis开发步骤"><a href="#2-1-MyBatis开发步骤" class="headerlink" title="2.1 MyBatis开发步骤"></a>2.1 MyBatis开发步骤</h4><p>MyBatis官网地址：<a target="_blank" rel="noopener" href="http://www.mybatis.org/mybatis-3/">http://www.mybatis.org/mybatis-3/</a> </p>
<p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%873.png"></p>
<p><strong>MyBatis开发步骤：</strong></p>
<p>①添加MyBatis的坐标</p>
<p>②创建user数据表</p>
<p>③编写User实体类 </p>
<p>④编写映射文件UserMapper.xml</p>
<p>⑤编写核心文件SqlMapConfig.xml</p>
<p>⑥编写测试类</p>
<h4 id="2-2-环境搭建"><a href="#2-2-环境搭建" class="headerlink" title="2.2 环境搭建"></a>2.2 环境搭建</h4><p>1)导入 MyBatis 的坐标和其他相关坐标</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--mybatis坐标--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.mybatis<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.4.5<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--compile：默认值 他表示被依赖项目需要参与当前项目的编译，还有后续的测试，运行周期也参与                  其中，是一个比较强的依赖。打包的时候通常需要包含进去--&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--mysql驱动坐标--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span>    </span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>   </span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mysql-connector-java<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span>    </span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.1.6<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--runtime：表示被依赖项目无需参与项目的编译，不过后期的测试和运行周期需要其参与。与                      compile相比，跳过了编译而已。例如JDBC驱动，适用运行和测试阶段--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">scope</span>&gt;</span>runtime<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--单元测试坐标--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span>    </span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>    </span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span>    </span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.12<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--test：依赖项目仅仅参与测试相关的工作，包括测试代码的编译和执行，不会被打包，例如：                   junit--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--日志坐标--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span>    </span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>log4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>    </span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>log4j<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span>    </span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.2.12<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ol start="2">
<li> 创建user数据表</li>
</ol>
<p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%875.png"></p>
<ol start="3">
<li>编写User实体</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;    </span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> id;    </span><br><span class="line">	<span class="keyword">private</span> String username;    </span><br><span class="line">	<span class="keyword">private</span> String password;</span><br><span class="line">    <span class="comment">//省略get和set方法</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4)编写UserMapper映射文件</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">mapper</span>        </span></span><br><span class="line"><span class="meta">	<span class="meta-keyword">PUBLIC</span> <span class="meta-string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span>        </span></span><br><span class="line"><span class="meta">	<span class="meta-string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- mapper 为根元素节点， 一个 namespace 对应一个 dao --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;userMapper&quot;</span>&gt;</span>  </span><br><span class="line">    <span class="comment">&lt;!-- 1. id （必须配置）</span></span><br><span class="line"><span class="comment">        id是命名空间中的唯一标识符，可被用来代表这条语句。 </span></span><br><span class="line"><span class="comment">        一个命名空间（namespace） 对应一个 dao 接口, </span></span><br><span class="line"><span class="comment">        这个 id 也应该对应 dao 里面的某个方法（相当于方法的实现），</span></span><br><span class="line"><span class="comment">        因此 id 应该与方法名一致--&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 2.resultType  </span></span><br><span class="line"><span class="comment">        指定 resultType 返回值类型是 User 类型的，</span></span><br><span class="line"><span class="comment">        只需要指定 resultType 的类型，MyBatis 会自动将查询的结果</span></span><br><span class="line"><span class="comment">        映射成 JavaBean 中的属性。</span></span><br><span class="line"><span class="comment">        对于resultType=&quot;string&quot;</span></span><br><span class="line"><span class="comment">        string 在这里是一个别名，代表的是 java.lang.String </span></span><br><span class="line"><span class="comment">        对于引用数据类型，都是将大写字母转小写，</span></span><br><span class="line"><span class="comment">        比如 HashMap 对应的别名是 &#x27;hashmap&#x27;</span></span><br><span class="line"><span class="comment">        基本数据类型考虑到重复的问题，</span></span><br><span class="line"><span class="comment">        会在其前面加上 &#x27;_&#x27;，比如 byte 对应的别名是 &#x27;_byte&#x27;</span></span><br><span class="line"><span class="comment">    --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;findAll&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.itheima.domain.User&quot;</span>&gt;</span>        </span><br><span class="line">		select * from User    </span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ol start="5">
<li>编写MyBatis核心文件</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">configuration</span> <span class="meta-keyword">PUBLIC</span> <span class="meta-string">&quot;-//mybatis.org//DTD Config 3.0//EN“ &quot;</span>http://mybatis.org/dtd/mybatis-3-config.dtd<span class="meta-string">&quot;&gt;</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">&lt;configuration&gt;    </span></span></span><br><span class="line"><span class="meta-string"><span class="meta">	&lt;environments default=&quot;</span>development<span class="meta-string">&quot;&gt;        </span></span></span><br><span class="line"><span class="meta-string"><span class="meta">		&lt;environment id=&quot;</span>development<span class="meta-string">&quot;&gt;</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">        &lt;!--事务管理器 transactionManager</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">           在 MyBatis 中有两种类型的事务管理器</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">          （也就是 type=”[JDBC|MANAGED]”）：</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">           1.JDBC -- 这个配置就是直接使用了 JDBC 的提交和回滚设置，</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">           它依赖于从数据源得到的连接来管理事务作用域。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">           2.MANAGED – 这个配置几乎没做什么。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">           它从来不提交或回滚一个连接，</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">           而是让容器来管理事务的整个生命周期（比如 JEE 应用服务器的上下文）。 </span></span></span><br><span class="line"><span class="meta-string"><span class="meta">           默认情况下它会关闭连接，然而一些容器并不希望这样，</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">           因此需要将 closeConnection 属性设置为 false 来阻止它默认的关闭行为。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">           提示：如果使用 Spring + MyBatis，则没有必要配置事务管理器， </span></span></span><br><span class="line"><span class="meta-string"><span class="meta">           因为 Spring 模块会使用自带的管理器来覆盖前面的配置。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">        --&gt;</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">			&lt;transactionManager type=&quot;</span>JDBC<span class="meta-string">&quot;/&gt;</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">        &lt;!--  数据源 dataSource 元素使用标准的 JDBC 数据源接口</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              来配置 JDBC 连接对象的资源。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              许多 MyBatis 的应用程序会按示例中的例子来配置数据源。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              虽然这是可选的，但为了使用延迟加载，数据源是必须配置的。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              有三种内建的数据源类型（也就是 type=”[UNPOOLED|POOLED|JNDI]”）：</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              POOLED– 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来，</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              避免了创建新的连接实例时所必需的初始化和认证时间。 </span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              这是一种使得并发 Web 应用快速响应请求的流行处理方式。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              POOLED 属性：</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              driver – 这是 JDBC 驱动的 Java 类的完全限定名（并不是 JDBC 驱动中可能包含的                        数据源类）。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              url – 这是数据库的 JDBC URL 地址。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              username – 登录数据库的用户名。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              password – 登录数据库的密码。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              defaultTransactionIsolationLevel – 默认的连接事务隔离级别。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              poolMaximumActiveConnections – 在任意时间可以存在的活动（也就是正在使用）                                              连接数量，默认值：10</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              poolMaximumIdleConnections – 任意时间可能存在的空闲连接数。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              poolMaximumCheckoutTime – 在被强制返回之前，池中连接被检出（checked out）                                         时间，默认值：20000 毫秒（即 20 秒）</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              poolTimeToWait – 这是一个底层设置，如果获取连接花费了相当长的时间，连接池会打                                印状态日志并重新尝试获取一个连接（避免在误配置的情况下一直安                                静的失败），默认值：20000 毫秒（即 20 秒）。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              poolMaximumLocalBadConnectionTolerance – 这是一个关于坏连接容忍度的底层                                设置， 作用于每一个尝试从缓存池获取连接的线程. 如果这个线程                                获取到的是一个坏的连接，那么这个数据源允许这个线程尝试重新获                                取一个新的连接，默认值：3 (新增于 3.4.5)</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              poolPingQuery – 发送到数据库的侦测查询，用来检验连接是否正常工作并准备接受请                               求。默认是“NO PING QUERY SET”，这会导致多数数据库驱动失败                               时带有一个恰当的错误消息。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              poolPingEnabled – 是否启用侦测查询。若开启，需要设置 poolPingQuery 属性为                                 一个可执行的 SQL 语句（最好是一个速度非常快的 SQL 语                                     句），默认值：false。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              poolPingConnectionsNotUsedFor – 配置 poolPingQuery 的频率。可以被设置                               为和数据库连接超时时间一样，来避免不必要的侦测，默认值：0</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">              （即所有连接每一时刻都被侦测 — 当然仅当 poolPingEnabled 为 true 时适用）。</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">        --&gt;</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">			&lt;dataSource type=&quot;</span>POOLED<span class="meta-string">&quot;&gt;                </span></span></span><br><span class="line"><span class="meta-string"><span class="meta">				&lt;property name=&quot;</span>driver<span class="meta-string">&quot; value=&quot;</span>com.mysql.jdbc.Driver<span class="meta-string">&quot;/&gt;</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">				&lt;property name=&quot;</span>url<span class="meta-string">&quot; value=&quot;</span>jdbc:mysql:///test<span class="meta-string">&quot;/&gt;                </span></span></span><br><span class="line"><span class="meta-string"><span class="meta">				&lt;property name=&quot;</span>username<span class="meta-string">&quot; value=&quot;</span>root<span class="meta-string">&quot;/&gt;</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">				&lt;property name=&quot;</span>password<span class="meta-string">&quot; value=&quot;</span>root<span class="meta-string">&quot;/&gt;            </span></span></span><br><span class="line"><span class="meta-string"><span class="meta">			&lt;/dataSource&gt;        </span></span></span><br><span class="line"><span class="meta-string"><span class="meta">		&lt;/environment&gt;    </span></span></span><br><span class="line"><span class="meta-string"><span class="meta">	&lt;/environments&gt;    </span></span></span><br><span class="line"><span class="meta-string"><span class="meta">	</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">	&lt;mappers&gt; </span></span></span><br><span class="line"><span class="meta-string"><span class="meta">		&lt;mapper resource=&quot;</span>com/itheima/mapper/UserMapper.xml<span class="meta-string">&quot;/&gt; </span></span></span><br><span class="line"><span class="meta-string"><span class="meta">	&lt;/mappers&gt;</span></span></span><br><span class="line"><span class="meta-string"><span class="meta">&lt;/configuration&gt;</span></span></span><br><span class="line"><span class="meta-string"><span class="meta"></span></span></span><br></pre></td></tr></table></figure>

<p>注意：</p>
<ul>
<li><font color ='red'>默认的环境 ID（比如:default=”development”）</font>。</li>
<li><font color ='red'>每个 environment 元素定义的环境 ID（比如:id=”development”）</font>。</li>
<li><font color ='red'>事务管理器的配置（比如:type=”JDBC”）</font>。</li>
<li><font color ='red'>数据源的配置（比如:type=”POOLED”）</font>。</li>
</ul>
<p>默认的环境和环境 ID 是自解释的，因此一目了然。可以对环境随意命名，<font color ='red'>但一定要保证默认的环境 ID 要匹配其中一个环境 ID</font>。</p>
<h4 id="2-3-编写测试代码"><a href="#2-3-编写测试代码" class="headerlink" title="2.3 编写测试代码"></a>2.3 编写测试代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//加载核心配置文件</span></span><br><span class="line">InputStream resourceAsStream = Resources.getResourceAsStream(<span class="string">&quot;SqlMapConfig.xml&quot;</span>);</span><br><span class="line"><span class="comment">//获得 sqlSession 工厂对象</span></span><br><span class="line">SqlSessionFactory sqlSessionFactory = <span class="keyword">new</span>            </span><br><span class="line">                           SqlSessionFactoryBuilder().build(resourceAsStream);</span><br><span class="line"><span class="comment">//获得 sqlSession 对象</span></span><br><span class="line">SqlSession sqlSession = sqlSessionFactory.openSession();</span><br><span class="line"><span class="comment">//执行 sql 语句</span></span><br><span class="line">List&lt;User&gt; userList = sqlSession.selectList(<span class="string">&quot;userMapper.findAll&quot;</span>);</span><br><span class="line"><span class="comment">//打印结果</span></span><br><span class="line">System.out.println(userList);</span><br><span class="line"><span class="comment">//释放资源</span></span><br><span class="line">sqlSession.close();</span><br></pre></td></tr></table></figure>

<h4 id="2-4-小结"><a href="#2-4-小结" class="headerlink" title="2.4 小结"></a>2.4 小结</h4><p><strong>MyBatis开发步骤：</strong></p>
<p>①添加MyBatis的坐标</p>
<p>②创建user数据表</p>
<p>③编写User实体类 </p>
<p>④编写映射文件UserMapper.xml</p>
<p>⑤编写核心文件SqlMapConfig.xml</p>
<p>⑥编写测试类</p>
<h3 id="3-MyBatis的映射文件概述"><a href="#3-MyBatis的映射文件概述" class="headerlink" title="3. MyBatis的映射文件概述"></a>3. MyBatis的映射文件概述</h3><p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%876.png"></p>
<h3 id="4-MyBatis的增删改查操作"><a href="#4-MyBatis的增删改查操作" class="headerlink" title="4. MyBatis的增删改查操作"></a>4. MyBatis的增删改查操作</h3><h4 id="4-1-MyBatis的插入数据操作"><a href="#4-1-MyBatis的插入数据操作" class="headerlink" title="4.1 MyBatis的插入数据操作"></a>4.1 MyBatis的插入数据操作</h4><p><strong>1)编写UserMapper映射文件</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;userMapper&quot;</span>&gt;</span>    </span><br><span class="line">	<span class="tag">&lt;<span class="name">insert</span> <span class="attr">id</span>=<span class="string">&quot;add&quot;</span> <span class="attr">parameterType</span> = <span class="string">&quot; com.itheima.domain.User &quot;</span>&gt;</span>        </span><br><span class="line">		insert into user values(#&#123;id&#125;,#&#123;username&#125;,#&#123;password&#125;)    </span><br><span class="line">	<span class="tag">&lt;/<span class="name">insert</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>2)编写插入实体User的代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">InputStream resourceAsStream = Resources.getResourceAsStream(<span class="string">&quot;SqlMapConfig.xml&quot;</span>);</span><br><span class="line">SqlSessionFactory sqlSessionFactory = <span class="keyword">new</span> </span><br><span class="line">                        SqlSessionFactoryBuilder().build(resourceAsStream);</span><br><span class="line">SqlSession sqlSession = sqlSessionFactory.openSession();</span><br><span class="line"><span class="keyword">int</span> insert = sqlSession.insert(<span class="string">&quot;userMapper.add&quot;</span>, user);</span><br><span class="line">System.out.println(insert);</span><br><span class="line"><span class="comment">//提交事务</span></span><br><span class="line">sqlSession.commit();</span><br><span class="line">sqlSession.close();</span><br></pre></td></tr></table></figure>

<p><strong>3)插入操作注意问题</strong></p>
<p>• 插入语句使用insert标签</p>
<p>• 在映射文件中使用 parameterType 属性指定要插入的数据类型</p>
<p>• Sql 语句中使用#{实体属性名}方式引用实体中的属性值</p>
<p>• 插入操作使用的 API 是 sqlSession.insert(“命名空间.id”,实体对象);</p>
<p>• 插入操作涉及数据库数据变化，所以要使用 sqlSession 对象显示的提交事务，即 sqlSession.commit() </p>
<h4 id="4-2-MyBatis的修改数据操作"><a href="#4-2-MyBatis的修改数据操作" class="headerlink" title="4.2 MyBatis的修改数据操作"></a>4.2 MyBatis的修改数据操作</h4><p><strong>1)编写UserMapper映射文件</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;userMapper&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">&quot;update&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;com.itheima.domain.User&quot;</span>&gt;</span></span><br><span class="line">        update user set username=#&#123;username&#125;,password=#&#123;password&#125; where id=#&#123;id&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>2)编写修改实体User的代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">InputStream resourceAsStream =                                                                          Resources.getResourceAsStream(<span class="string">&quot;SqlMapConfig.xml&quot;</span>);</span><br><span class="line">SqlSessionFactory sqlSessionFactory = <span class="keyword">new</span>                                                              SqlSessionFactoryBuilder().build(resourceAsStream);</span><br><span class="line">SqlSession sqlSession = sqlSessionFactory.openSession();</span><br><span class="line"><span class="keyword">int</span> update = sqlSession.update(<span class="string">&quot;userMapper.update&quot;</span>, user);</span><br><span class="line">System.out.println(update);</span><br><span class="line">sqlSession.commit();</span><br><span class="line">sqlSession.close();</span><br></pre></td></tr></table></figure>

<p><strong>3)修改操作注意问题</strong></p>
<p>• 修改语句使用 update 标签</p>
<p>• 修改操作使用的API是sqlSession.update(“命名空间.id”,实体对象);</p>
<h4 id="4-3-MyBatis的删除数据操作"><a href="#4-3-MyBatis的删除数据操作" class="headerlink" title="4.3 MyBatis的删除数据操作"></a>4.3 MyBatis的删除数据操作</h4><p><strong>1)编写UserMapper映射文件</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;userMapper&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">delete</span> <span class="attr">id</span>=<span class="string">&quot;delete&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;java.lang.Integer&quot;</span>&gt;</span></span><br><span class="line">        delete from user where id=#&#123;id&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">delete</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>2)编写删除数据的代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">InputStream resourceAsStream = Resources.getResourceAsStream(<span class="string">&quot;SqlMapConfig.xml&quot;</span>);</span><br><span class="line">SqlSessionFactory sqlSessionFactory = <span class="keyword">new</span> SqlSessionFactoryBuilder().build(resourceAsStream);</span><br><span class="line">SqlSession sqlSession = sqlSessionFactory.openSession();</span><br><span class="line"><span class="keyword">int</span> delete = sqlSession.delete(<span class="string">&quot;userMapper.delete&quot;</span>,<span class="number">3</span>);</span><br><span class="line">System.out.println(delete);</span><br><span class="line">sqlSession.commit();</span><br><span class="line">sqlSession.close();</span><br></pre></td></tr></table></figure>

<p><strong>3)删除操作注意问题</strong></p>
<p>• 删除语句使用delete标签</p>
<p>•Sql语句中使用#{任意字符串}方式引用传递的单个参数</p>
<p>•删除操作使用的API是sqlSession.delete(“命名空间.id”,Object);</p>
<h4 id="4-4-知识小结"><a href="#4-4-知识小结" class="headerlink" title="4.4 知识小结"></a>4.4 知识小结</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">增删改查映射配置与API：</span><br><span class="line">查询数据： List&lt;User&gt; userList = sqlSession.selectList(<span class="string">&quot;userMapper.findAll&quot;</span>);</span><br><span class="line">         &lt;select id=<span class="string">&quot;findAll&quot;</span> resultType=<span class="string">&quot;com.itheima.domain.User&quot;</span>&gt;</span><br><span class="line">                select * from User</span><br><span class="line">         &lt;/select&gt;</span><br><span class="line">添加数据： sqlSession.insert(<span class="string">&quot;userMapper.add&quot;</span>, user);</span><br><span class="line">         &lt;insert id=<span class="string">&quot;add&quot;</span> parameterType=<span class="string">&quot;com.itheima.domain.User&quot;</span>&gt;</span><br><span class="line">             <span class="function">insert into user <span class="title">values</span><span class="params">(#&#123;id&#125;,#&#123;username&#125;,#&#123;password&#125;)</span></span></span><br><span class="line"><span class="function">         &lt;/insert&gt;</span></span><br><span class="line"><span class="function">修改数据： sqlSession.<span class="title">update</span><span class="params">(<span class="string">&quot;userMapper.update&quot;</span>, user)</span></span>;</span><br><span class="line">         &lt;update id=<span class="string">&quot;update&quot;</span> parameterType=<span class="string">&quot;com.itheima.domain.User&quot;</span>&gt;</span><br><span class="line">               update user set username=#&#123;username&#125;,password=#&#123;password&#125; where                                           id=#&#123;id&#125;</span><br><span class="line">         &lt;/update&gt;</span><br><span class="line">删除数据：sqlSession.delete(<span class="string">&quot;userMapper.delete&quot;</span>,<span class="number">3</span>);</span><br><span class="line">        &lt;delete id=<span class="string">&quot;delete&quot;</span> parameterType=<span class="string">&quot;java.lang.Integer&quot;</span>&gt;</span><br><span class="line">             delete from user where id=#&#123;id&#125;</span><br><span class="line">        &lt;/delete&gt;</span><br></pre></td></tr></table></figure>

<h3 id="5-MyBatis核心配置文件概述"><a href="#5-MyBatis核心配置文件概述" class="headerlink" title="5. MyBatis核心配置文件概述"></a>5. MyBatis核心配置文件概述</h3><h4 id="5-1-MyBatis核心配置文件层级关系"><a href="#5-1-MyBatis核心配置文件层级关系" class="headerlink" title="5.1 MyBatis核心配置文件层级关系"></a>5.1 MyBatis核心配置文件层级关系</h4><p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%877.png"></p>
<h4 id="5-2-MyBatis常用配置解析"><a href="#5-2-MyBatis常用配置解析" class="headerlink" title="5.2 MyBatis常用配置解析"></a>5.2 MyBatis常用配置解析</h4><p><strong>1)environments标签</strong></p>
<p>数据库环境的配置，支持多环境配置</p>
<p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%878.png"></p>
<p>其中，事务管理器（transactionManager）类型有两种：</p>
<p>•JDBC：这个配置就是直接使用了JDBC 的提交和回滚设置，它依赖于从数据源得到的连接来管理事务作用域。</p>
<p>•MANAGED：这个配置几乎没做什么。它从来不提交或回滚一个连接，而是让容器来管理事务的整个生命周期（比如 JEE 应用服务器的上下文）。 默认情况下它会关闭连接，然而一些容器并不希望这样，因此需要将 closeConnection 属性设置为 false 来阻止它默认的关闭行为。</p>
<p>其中，数据源（dataSource）类型有三种：</p>
<p>• UNPOOLED：这个数据源的实现只是每次被请求时打开和关闭连接。</p>
<p>• POOLED：这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来。</p>
<p>• JNDI：这个数据源的实现是为了能在如 EJB 或应用服务器这类容器中使用，容器可以集中或在外部配置数据源，然后放置一个 JNDI 上下文的引用。</p>
<p><strong>2)mapper标签</strong></p>
<p>该标签的作用是加载映射的，加载方式有如下几种：</p>
<p>• 使用相对于类路径的资源引用，例如：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">resource</span>=<span class="string">&quot;org/mybatis/builder/AuthorMapper.xml&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>• 使用完全限定资源定位符（URL），例如：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">url</span>=<span class="string">&quot;file:///var/mappers/AuthorMapper.xml&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>• 使用映射器接口实现类的完全限定类名，例如：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">class</span>=<span class="string">&quot;org.mybatis.builder.AuthorMapper&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>• 将包内的映射器接口实现全部注册为映射器，例如：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">package</span> <span class="attr">name</span>=<span class="string">&quot;org.mybatis.builder&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>3)Properties标签</strong></p>
<p>实际开发中，习惯将数据源的配置信息单独抽取成一个properties文件，该标签可以加载额外配置的properties文件。</p>
<p>  <img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%879.png"></p>
<p><strong>4)typeAliases标签</strong></p>
<p>类型别名是为Java 类型设置一个短的名字。原来的类型名称配置如下</p>
<p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%8710.png"></p>
<p>配置typeAliases，为com.itheima.domain.User定义别名为user</p>
<p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%8711.png"></p>
<p>上面我们是自定义的别名，mybatis框架已经为我们设置好的一些常用的类型的别名</p>
<p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%8712.png"></p>
<h4 id="5-3-知识小结"><a href="#5-3-知识小结" class="headerlink" title="5.3 知识小结"></a>5.3 知识小结</h4><p><strong>核心配置文件常用配置：</strong></p>
<p>properties标签：该标签可以加载外部的properties文件</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">properties</span> <span class="attr">resource</span>=<span class="string">&quot;jdbc.properties&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">properties</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>typeAliases标签：设置类型别名</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">typeAlias</span> <span class="attr">type</span>=<span class="string">&quot;com.itheima.domain.User&quot;</span> <span class="attr">alias</span>=<span class="string">&quot;user&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">typeAlias</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>mappers标签：加载映射配置</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">resource</span>=<span class="string">&quot;com/itheima/mapper/UserMapping.xml&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>environments标签：数据源环境配置标签</p>
<p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%8713.png"></p>
<h3 id="6-MyBatis相应API"><a href="#6-MyBatis相应API" class="headerlink" title="6.MyBatis相应API"></a>6.MyBatis相应API</h3><h4 id="6-1-SqlSession工厂构建器SqlSessionFactoryBuilder"><a href="#6-1-SqlSession工厂构建器SqlSessionFactoryBuilder" class="headerlink" title="6.1 SqlSession工厂构建器SqlSessionFactoryBuilder"></a>6.1 SqlSession工厂构建器SqlSessionFactoryBuilder</h4><p>常用API：SqlSessionFactory  build(InputStream inputStream)</p>
<p>通过加载mybatis的核心文件的输入流的形式构建一个 SqlSessionFactory 对象</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String resource = <span class="string">&quot;org/mybatis/builder/mybatis-config.xml&quot;</span>; </span><br><span class="line">InputStream inputStream = Resources.getResourceAsStream(resource); </span><br><span class="line">SqlSessionFactoryBuilder builder = <span class="keyword">new</span> SqlSessionFactoryBuilder(); </span><br><span class="line">SqlSessionFactory factory = builder.build(inputStream);</span><br></pre></td></tr></table></figure>

<p>其中， Resources 工具类，这个类在 org.apache.ibatis.io 包中。Resources 类帮助你从类路径下、文件系统或一个 web URL 中加载资源文件。</p>
<h4 id="6-2-SqlSession工厂对象SqlSessionFactory"><a href="#6-2-SqlSession工厂对象SqlSessionFactory" class="headerlink" title="6.2 SqlSession工厂对象SqlSessionFactory"></a>6.2 SqlSession工厂对象SqlSessionFactory</h4><p>SqlSessionFactory 有多个个方法创建SqlSession 实例。常用的有如下两个：</p>
<p><img src="https://gitee.com/AD-Gai-Code/pic-go/raw/master/%E5%9B%BE%E7%89%8714.png" alt="1552653723002"></p>
<h4 id="6-3-SqlSession会话对象"><a href="#6-3-SqlSession会话对象" class="headerlink" title="6.3 SqlSession会话对象"></a>6.3 SqlSession会话对象</h4><p>SqlSession 实例在 MyBatis 中是非常强大的一个类。在这里你会看到所有执行语句、提交或回滚事务和获取映射器实例的方法。</p>
<p>执行语句的方法主要有：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;T&gt; <span class="function">T <span class="title">selectOne</span><span class="params">(String statement, Object parameter)</span> </span></span><br><span class="line"><span class="function">&lt;E&gt; List&lt;E&gt; <span class="title">selectList</span><span class="params">(String statement, Object parameter)</span> </span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">insert</span><span class="params">(String statement, Object parameter)</span> </span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">update</span><span class="params">(String statement, Object parameter)</span> </span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">delete</span><span class="params">(String statement, Object parameter)</span></span></span><br><span class="line"><span class="function"></span></span><br></pre></td></tr></table></figure>

<p>操作事务的方法主要有：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">commit</span><span class="params">()</span>  </span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">rollback</span><span class="params">()</span> </span></span><br></pre></td></tr></table></figure>








    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Mybatis/" rel="tag"># Mybatis</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/09/04/Maven%E5%9B%9E%E9%A1%BE/" rel="prev" title="Maven 学习">
                  <i class="fa fa-chevron-left"></i> Maven 学习
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/09/04/Servlet%EF%BC%8C%E6%88%91%E8%BF%98%E6%98%AF%E7%88%B1%E4%BD%A0%E7%9A%84/" rel="next" title="Servlet，我还是爱你的">
                  Servlet，我还是爱你的 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">AiLaodu</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="https://cdn.jsdelivr.net/npm/algoliasearch@4.10.5/dist/algoliasearch-lite.umd.js" integrity="sha256-HWlivbjXc58GuU4EIZziqIE83FFZ/da42de13pGZnMA=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/instantsearch.js@4.30.2/dist/instantsearch.production.min.js" integrity="sha256-eqhx/eer5fsD7YooSb21wsfJaQkJ/4gF3bmRBZP7q2o=" crossorigin="anonymous"></script><script src="/js/third-party/search/algolia-search.js"></script>





  





</body>
</html>
